<template>
  <el-dialog title="添加待收账单" :model-value="visible" width="520px" :fullscreen="mobile" @close="handleAddBillingClose">
    <el-form :model="receivablesForm" :rules="receivablesRules" ref="receivablesFormRef" label-width="100px">
      <el-form-item prop="type" label-width="0">
        <div style="display: flex;justify-content: center;width: 100%;">
          <el-radio-group v-model="receivablesForm.type">
            <el-radio label="1">单笔添加</el-radio>
            <el-radio label="2">批量添加</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="费用名称" prop="name">
        <el-input v-model="receivablesForm.name" placeholder="请输入费用名称"></el-input>
      </el-form-item>
      <el-form-item label="账单金额" prop="money">
        <el-input v-model="receivablesForm.money" placeholder="请输入账单金额"></el-input>
      </el-form-item>
      <el-form-item label="入住周期" required>
        <el-row>
          <el-col :span="11">
            <el-form-item label-width="0" prop="billCycleBegin">
              <el-date-picker
                v-model="receivablesForm.billCycleBegin"
                :editable="false"
                type="date"
                placeholder="请选择开始日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <div style="text-align: center;">-</div>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="0" prop="billCycleEnd">
              <el-date-picker
                v-model="receivablesForm.billCycleEnd"
                type="date"
                :editable="false"
                placeholder="请选择结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="待收日期" prop="noticeDate" v-if="receivablesForm.type === '1'">
        <el-date-picker
          v-model="receivablesForm.noticeDate"
          type="date"
          placeholder="请选择记账日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="收款时间" required v-if="receivablesForm.type === '2'">
        <el-row :gutter="20" style="width: 100%;">
          <el-col :span="11">
            <el-form-item prop="collectionType" required>
              <el-select v-model="receivablesForm.collectionType">
                <el-option label="每1月" value="1"></el-option>
                <el-option label="每2月" value="2"></el-option>
                <el-option label="每3月" value="3"></el-option>
                <el-option label="每1天" value="4"></el-option>
                <el-option label="每3天" value="5"></el-option>
                <el-option label="每7天" value="6"></el-option>
                <el-option label="每15天" value="7"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-if="['1', '2', '3'].includes(receivablesForm.collectionType)">
            <el-form-item prop="collectionDateType" required>
              <el-select v-model="receivablesForm.collectionDateType">
                <el-option :label="item + '号收款'" :value="item" v-for="item in 31" :key="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <el-table :data="incompleteList" class="mt20" style="width: 100%" border>
      <el-table-column prop="name" label="费用名称" />
      <el-table-column prop="money" label="金额" />
      <el-table-column prop="noticeDate" label="待收日期"  />
      <el-table-column label="操作" :width="60">
        <template #default="scope">
          <el-button link type="danger" class="fs-large" :icon="CircleCloseFilled" @click="handleCloseBilling(scope.$index)" />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleAddBillingClose">取消</el-button>
        <el-button type="primary" plain @click="handleAddBillingCreate">
          生成账单
        </el-button>
        <el-button v-if="incompleteList.length > 0" type="primary" @click="handleAddBillingOk">完成</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="ReceivablesDl">
import { CircleCloseFilled } from '@element-plus/icons-vue'
import useAppStore from '@/store/modules/app'
import { parseTime } from '@/utils/ruoyi'
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean
  },
  type: {
    type: String
  },
  form: {
    type: Object,
    default: () => {}
  }
})
const incompleteList = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  receivablesForm: {
    type: '1',
    name: undefined,
    money: undefined,
    noticeDate: parseTime(new Date(), '{y}-{m}-{d}'),
    collectionType: '1',
    collectionDateType: 1,
    billCycleBegin: parseTime(new Date(), '{y}-{m}-{d}'),
    billCycleEnd: parseTime(new Date(), '{y}-{m}-{d}')
  },
  receivablesRules: {
    name: [{ required: true, message: "请输入费用名称", trigger: "blur" }],
    money: [
      { required: true, message: "请输入账单金额", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的账单金额", trigger: ["blur", "change"] }
    ],
    noticeDate: [{ required: true, message: "请选择记账日期", trigger: "blur" }],
    billCycleBegin: [{ required: true, type: 'date', message: "请选择开始日期", trigger: "blur" }],
    billCycleEnd: [{ required: true, type: 'date', message: "请选择结束日期", trigger: ["blur"] }],
  },
})

const { receivablesForm, receivablesRules } = toRefs(data)

watch(() => props.visible, (value) => {
  if (value) {
    proxy.resetForm('receivablesFormRef')
    incompleteList.value = []
    if (props.type === 'edit') {
      receivablesForm.value = { ...props.form }
    }
  }
})

// 获取日期区间每个月固定日期的集合
function isLeapYear(year) {
  if (year % 4 === 0) {
      if (year % 100 === 0) {
          return year % 400 === 0;
      } else {
          return true
      }
  } else {
      return false
  }
}

// 生成待收账日期
function getFirstDatesInRange(billCycleBegin, billCycleEnd, range, date) {
  // debugger
  const result = [];
  // 以月份为周期
  if (range <= 3) {
    let currentDate = new Date();
    // 结束日期月份小于当前月份 且 小于一个收款周期的，返回 时间周期错误，请重新选择
    let year = billCycleEnd.getFullYear() - new Date().getFullYear()
    // 间隔月份
    const spaceMonth = (year * 12 + billCycleEnd.getMonth()) - new Date().getMonth()
    if (spaceMonth < range + 1) {
      return []
    }
    while (currentDate.setDate(1) <= billCycleEnd.setDate(1)) {

      let billingDate = date
      // 如果收款日超出当月最后一天，需将收款日改成当月最后一天
      if (currentDate.getMonth() === 1 && date > 28) {
        if (isLeapYear(currentDate.getFullYear())) billingDate = 29
        else billingDate = 28
      } else if ([3, 5, 8, 10].includes(currentDate.getMonth()) && date === 31) {
        billingDate = 30
      }
      // 生成收款日，并将收款日加入数组
      result.push(parseTime(new Date(currentDate.getFullYear(), currentDate.getMonth(), billingDate), '{y}-{m}-{d}'))
      // 收款周期增加
      currentDate.setMonth(currentDate.getMonth() + range)
    }
  } else {
    // 天数为周期
    let currentDate = new Date();
    let rangeDate = 0
    let spaceDate = Math.ceil((billCycleEnd.getTime() - currentDate.getTime()) / (1000 * 3600 * 24))
    switch (range) {
      case 4:
        rangeDate = 1
        break;
      case 5:
        rangeDate = 3
        break;
      case 6:
        rangeDate = 7
        break;
      case 7:
        rangeDate = 15
        break;
      default:
        break;
    }
    if (spaceDate < 0) {
      return []
    }
    while (currentDate <= billCycleEnd) {
      // 生成收款日，并将收款日加入数组
      result.push(parseTime(currentDate, '{y}-{m}-{d}'))
      currentDate.setDate(currentDate.getDate() + rangeDate)
    }
  }

  // 固定第一个待收日期为当天
  result[0] = parseTime(new Date(), '{y}-{m}-{d}')
  return result
}
function handleAddBillingClose() {
  emit('cancel')
}
// 生成待收账单
function handleAddBillingCreate() {
  proxy.$refs['receivablesFormRef'].validate(valid => {
    if (valid) {
      if (receivablesForm.value.type === '1') {
        incompleteList.value.push({
          name: receivablesForm.value.name,
          money: receivablesForm.value.money,
          noticeDate: receivablesForm.value.noticeDate,
          billCycleBegin: receivablesForm.value.billCycleBegin,
          billCycleEnd: receivablesForm.value.billCycleEnd,
        })
        receivablesForm.value.name = ""
        receivablesForm.value.money = ""
      } else {
        const billCycleBegin = new Date(receivablesForm.value.billCycleBegin)
        const billCycleEnd = new Date(receivablesForm.value.billCycleEnd)
        const dates = getFirstDatesInRange(billCycleBegin, billCycleEnd, Number(receivablesForm.value.collectionType), receivablesForm.value.collectionDateType)
        if (dates.length === 0) {
          proxy.$modal.msgError("时间周期错误，请重新选择");
        } else {
          for (const key in dates) {
            console.log(dayjs(dates[key]).endOf('month').format('YYYY-MM-DD'))
            incompleteList.value.push({
              name: receivablesForm.value.name,
              money: receivablesForm.value.money,
              noticeDate: dates[key],
              billCycleBegin: dates[key],
              billCycleEnd: dayjs(dates[key]).endOf('month').format('YYYY-MM-DD'),
            })
          }
        }
      }
      // 排序
      incompleteList.value.sort((pre, next) => (new Date(pre.noticeDate) - new Date(next.noticeDate)))
    }
  })
}
// 添加待收账单
function handleAddBillingOk() {
  emit('ok', incompleteList.value)
}
// 删除待添加表格行
function handleCloseBilling(index) {
  incompleteList.value.splice(index, 1)
}

</script>